class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        nums = [[0] * n for _ in range(n)]
        # startx, starty = 0, 0
        # loop, mid = n // 2, n // 2
        # count = 1
        #
        # for offset in range(1, loop + 1):
        #     # 从左到右，左闭右开
        #     for i in range(starty, n - offset):
        #         nums[startx][i] = count
        #         count += 1
        #     for i in range(startx, n - offset):
        #         nums[i][n - offset] = count
        #         count += 1
        #     for i in range(n - offset, starty, -1):
        #         nums[n - offset][i] = count
        #         count += 1
        #     for i in range(n - offset,startx,-1):
        #         nums[i][starty] = count
        #         count += 1
        #
        #     startx += 1
        #     starty += 1
        #
        # if n % 2 != 0 :
        #     nums[mid][mid] = count
        # return nums
        top, bottom, left, right = 0, n - 1, 0, n - 1
        count = 1
        while top <= bottom and left <= right:
            for i in range(left, right + 1):
                nums[top][i] = count
                count += 1
            top += 1

            for i in range(top, bottom + 1):
                nums[i][right] = count
                count += 1
            right -= 1

            for i in range(right, left - 1, -1):
                nums[bottom][i] = count
                count += 1
            bottom -= 1

            for i in range(bottom, top - 1, -1):
                nums[i][left] = count
                count += 1
            left += 1

        return nums


if __name__ == '__main__':
    for row in Solution().generateMatrix(4):
        print(row)
